package core

import (
	"net/tcpclient"
	"share/msg"
	"time"
	"util/log"
)

type serv struct {
	app  msg.AppInfo
	conn *tcpclient.Tcpconn
}

type route struct {
	services map[uint64]serv
	quit     chan bool
}

func (r *route) Start() {
	r.quit = make(chan bool, 1)
	go r.run()
}

func (r *route) run() {
	tick := time.NewTicker(5 * time.Second)
	defer tick.Stop()
loop:
	for {
		select {
		case <-tick.C:
			r.scan()
		case <-r.quit:
			break loop
		}
	}
}

func (r *route) scan() {
	applist := gate.appClient.AppList()
	for _, app := range applist {
		if app.AppType == msg.AT_GATE || app.AppType == msg.AT_DB || app.AppType == msg.AT_LISTER {
			continue
		}

		if _, dup := r.services[app.AppId]; !dup {
			s := serv{}
			s.app = app
			s.conn = tcpclient.CreateTcpclient()
			r.services[app.AppId] = s
		}
	}

	del := make([]uint64, 0, 10)
	for k, s := range r.services {
		if !s.conn.Connected() {
			if err := s.conn.Connect(s.app.AppIp, s.app.AppPort); err != nil {
				log.LogError("connect app failed", s.app.AppIp, ":", s.app.AppPort)
				del = append(del, k)
			} else {
				log.TraceInfo("route", "connect to app ", s.app.AppIp, ":", s.app.AppPort)
			}
		}
	}

	for _, d := range del {
		delete(r.services, d)
	}
}

func (r *route) Shutdown() {
	r.quit <- true
}

func createRoute() *route {
	r := &route{}
	r.services = make(map[uint64]serv)
	return r
}
